// routes/cards/findAllByGroup.js
const express = require('express');
const pool = require('../../config/pool'); // 使用连接池
const router = express.Router();
const isAdmin = require('../../middleware/isAdmin');

router.post('/', isAdmin, (req, res) => {
    const processed_by = req.user_id;
    const { order_id, status, notes } = req.body;
    // 根据order_id查询订单
    const query = `SELECT * FROM orders where id =?`;
    pool.query(query, [order_id], (err, results) => {
        if (err) {
            return res.json({
                code: 0,
                message: '数据库错误',
                success: false
            });
        }
        if (results.length === 0) {
            return res.json({
                code: 0,
                message: '订单不存在',
                success: false
            });
        }
        const order = results[0];
        const old_status = order.status;
        const new_status = status
        // 更新订单表并向order_processing_records表中添加一条记录
        const updateQuery = `UPDATE orders SET status =? WHERE id =?`;
        const insertQuery = `INSERT INTO order_processing_records (order_id, old_status, new_status, notes, processed_by) VALUES (?,?,?,?,?)`;
        pool.query(updateQuery, [new_status, order_id], (err, results) => {
            if (err) {
                return res.json({
                    code: 0,
                    message: '数据库错误',
                    success: false
                });
            }
            console.log('status:' , status)
            pool.query(insertQuery, [order_id, old_status, new_status,  notes, processed_by], (err, results) => {
                if (err) {
                    return res.json({
                        code: 0,
                        message: '数据库错误',
                        success: false
                    });
                }
                res.json({
                    code: 1,
                    message: '订单处理成功',
                    success: true
                });
            });
        });
    })
});

module.exports = router;